package com.his.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.his.common.PageParam;
import com.his.common.Rsp;
import com.his.entity.*;
import com.his.mapper.DrawbackMedicinalMapper;
import com.his.mapper.RecipelChildMapper;
import com.his.mapper.RecipelMapper;
import com.his.service.OrderService;
import com.his.service.RecipelService;
import com.his.utils.MyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (Recipel)表服务实现类
 *
 * @author makejava
 * @since 2020-10-23 18:14:29
 */
@Service("recipelService")
public class RecipelServiceImpl implements RecipelService {
    @Resource
    private RecipelMapper recipelMapper;

    @Resource
    private RecipelChildMapper recipelChildMapper;

    @Resource
    private DrawbackMedicinalMapper drawbackMedicinalMapper;

    @Resource
    private OrderService orderService;

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public Rsp deleteByIdLogic(Integer id) {
        if (this.recipelMapper.deleteByIdLogic(id) > 0) {
            return Rsp.success(null).msg("删除成功");
        } else {
            return Rsp.fail();
        }
    }

    /**
     * 分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public PageInfo<Recipel> searchSomeRecipelPage(PageParam<Recipel> pageParam, HisUser user) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for (int i = 0; i < pageParam.getOrderParams().length; i++) {
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }
        Recipel model = pageParam.getModel();
        if (user.getRoles().contains("nurse")) {
            model.setPatientId(user.getId());
        } else if (user.getRoles().contains("doctor")) {
            model.setDoctorId(user.getId());
        }
        return new PageInfo<>(recipelMapper.queryAllByModel(model));
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Rsp queryById(Integer id) {
        Recipel recipel = this.recipelMapper.queryById(id);
        if (StringUtils.isEmpty(recipel)) {
            return Rsp.fail();
        } else {
            return Rsp.success(recipel);
        }
    }

    /**
     * 查询所有通过实体类属性
     *
     * @param recipel 实例对象
     * @return 查询的结果
     */
    @Override
    public List<Recipel> queryAll(Recipel recipel) {
        return this.recipelMapper.queryAll(recipel);
    }

    /**
     * 新增数据
     *
     * @param recipel 实例对象
     * @return 实例对象
     */
    @Override
    public Rsp insert(Recipel recipel) {
        recipel.setStatus("0");
        recipel.setCreateTime(new Date());
        recipel.setIsDelete(0);
        int insert = this.recipelMapper.insert(recipel);
        if (insert > 0) {
            return Rsp.success(recipel);
        } else {
            return Rsp.fail();
        }
    }

    /**
     * 修改数据
     *
     * @param recipel 实例对象
     * @return 实例对象
     */
    @Override
    public Rsp update(Recipel recipel) {
        int update = this.recipelMapper.update(recipel);
        if (update > 0) {
            return Rsp.success(update).msg("修改成功");
        } else {
            return Rsp.fail();
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.recipelMapper.deleteById(id) > 0;
    }

    @Override
    public PageInfo<Patient> getPatientRecipelInfo(PageParam<Patient> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<Patient> patientList = recipelMapper.selectPatientRecAndAdv(pageParam.getModel());

        return null;
    }

    /**
     * 护士核对处方
     *
     * @param recipel
     * @return
     */
    @Override
    public Rsp recipelSure(Recipel recipel) {
        Integer recipelSure = recipelMapper.recipelSure(recipel.getId());
        if (recipelSure > 0) {
            return Rsp.success(recipel).msg("核对成功");
        } else {
            return Rsp.fail().msg("核对失败");
        }
    }

    /**
     * 药房确认拿药,生成订单
     *
     * @param recipel
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Rsp medicinalSure(String token, Recipel recipel) {
        Integer medicinalSure = recipelMapper.medicinalSure(recipel.getId());
        if (medicinalSure > 0) {
            //根据id查处方
            Recipel queryById = recipelMapper.queryById(recipel.getId());
            //根据处方生成订单
            Order order = new Order();
            order.setPatientId(queryById.getPatientId());
            order.setCategoryId(2);
            try {
                order.setCreateUserId(MyUtil.getUserByToken(token));
            } catch (Exception e) {
                e.printStackTrace();
                return Rsp.fail().msg("登录账户验证信息错误");
            }
            //查询当前ID所有子处方
            RecipelChild recipelChild = new RecipelChild();
            recipelChild.setRecipelId(recipel.getId());
            List<RecipelChild> recipelList = recipelChildMapper.queryAllByModel(recipelChild);
            //计算总价total
            //获取退药总金额
            BigDecimal total = new BigDecimal("0");
            String descript = "药品款项:";
            //累加总价 追加描述
            for (RecipelChild temp : recipelList) {
                total = total.add(temp.getPrice().multiply(new BigDecimal(temp.getCount())));
                descript = descript + temp.getMedicinalName() + temp.getCount() + "个\n";
            }
            order.setTotalMoney(total.doubleValue());
            order.setDescript(descript);
            order.setStatus("0");
            order.setCreateTime(new Date());
            order.setIsDelete("0");
            orderService.insert(order);
            //获取自动生成的主键
            Integer id = order.getId();
            System.out.println("自动生成的主键" + id);
            queryById.setOrderId(id);
            //订单id写入数据库
            recipelMapper.update(queryById);
            return Rsp.success(recipel).msg("核对成功");
        } else {
            return Rsp.fail().msg("核对失败");
        }
    }

    /**
     * 药房查药("medSearchSomeRecipelPage")
     */
    @Override
    public PageInfo<Recipel> medSearchSomeRecipelPage(PageParam<Recipel> pageParam) {
        if (!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())) {
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for (int i = 0; i < pageParam.getOrderParams().length; i++) {
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            return new PageInfo<Recipel>(recipelMapper.medSuperSearch(pageParam.getSuperSearchKeyWord()));
        }
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for (int i = 0; i < pageParam.getOrderParams().length; i++) {
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }
        return new PageInfo<Recipel>(recipelMapper.medQueryAllByModel(pageParam.getModel()));
    }

    /**
     * 医生申请退药
     *
     * @param recipel
     * @return
     */
    @Override
    public Rsp drawbackMedicinal(Recipel recipel) {
        if (recipel.getId() == null) {
            return Rsp.fail().msg("主键不能为空");
        }
        //处方状态码改为3
        recipel.setStatus("3");
        recipelMapper.update(recipel);
        //查询当前ID所有子处方
        RecipelChild recipelChild = new RecipelChild();
        recipelChild.setRecipelId(recipel.getId());
        List<RecipelChild> recipelList = recipelChildMapper.queryAllByModel(recipelChild);
        //获取退药总金额
        BigDecimal total = new BigDecimal("0");
        //累加
        for (RecipelChild temp : recipelList) {
            total = total.add(temp.getPrice().multiply(new BigDecimal(temp.getCount())));
        }
        DrawbackMedicinal drawbackMedicinal = new DrawbackMedicinal();
        drawbackMedicinal.setPatientId(recipel.getPatientId());
        drawbackMedicinal.setRecipelId(recipel.getId());
        drawbackMedicinal.setDrawbackMoney(total.doubleValue());
        drawbackMedicinal.setCreateTime(new Date());
        drawbackMedicinal.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        drawbackMedicinal.setDrawbackReason("测试原因");
        drawbackMedicinal.setStatus(0);
        //生成退药申请单
        int insert = drawbackMedicinalMapper.insert(drawbackMedicinal);
        return insert > 0 ? Rsp.success(drawbackMedicinal).msg("已申请退药") : Rsp.fail().msg("提交失败");
    }

    /**
     * 逻辑删除病人ID下的处方
     *
     * @return
     */
    @Override
    public Rsp deleteByPatientIdLogic(Integer id) {
        Integer deleteByPatientIdLogic = recipelMapper.deleteByPatientIdLogic(id);
        if (deleteByPatientIdLogic > 0) {
            return Rsp.success(null).msg("逻辑删除成功");
        } else {
            return Rsp.fail().msg("逻辑删除失败");
        }
    }


}
